package report

import (
	"../common"
	"../web"
	"encoding/json"
	"strconv"
	"strings"
	"time"
)

type FailStatisticsObj struct {
	common.BaseHandler
}

type FailStatisticsDetailObj struct {
	common.BaseHandler
}

type FailStatisticsPageObj struct {
	common.BaseHandler
}

func (self *FailStatisticsObj) Prepare() {}

func (self *FailStatisticsObj) ParameterCheck() bool {
	c_begin := strings.TrimSpace(self.Ctx.Params["fromdate"])
	c_end := strings.TrimSpace(self.Ctx.Params["todate"])
	if c_begin == "" {
		return false
	}
	s_begin, err := time.Parse("2006-01-02 15:04:05", c_begin)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Query Begin Date is invalid.")
		return false
	}
	if len(c_begin) != 19 {
		self.TmplData["error"] = common.GetText(self.Lang, "Query Begin Date is invalid.")
		return false
	}
	if c_end == "" {
		return false
	}
	s_end, err := time.Parse("2006-01-02 15:04:05", c_end)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Query End Date is invalid.")
		return false
	}
	if len(c_end) != 19 {
		self.TmplData["error"] = common.GetText(self.Lang, "Query End Date is invalid.")
		return false
	}
	if c_begin == c_end {
		self.TmplData["error"] = common.GetText(self.Lang, "The selected time period is not a valid interval.")
		return false
	}
	if s_begin.After(s_end) {
		s_begin, s_end = s_end, s_begin
		c_begin, c_end = c_end, c_begin
	}
	if s_begin.Add(3600 * 24 * 1000 * time.Second).Before(s_end) {
		self.TmplData["error"] = common.GetText(self.Lang, "Date interval can select up to 1000 days.")
		return false
	}

	c_begin = s_begin.Format("2006-01-02 15:04:05")
	c_end = s_end.Format("2006-01-02 15:04:05")

	self.Sqlparas = append(self.Sqlparas, c_begin)
	self.Sqlparas = append(self.Sqlparas, c_end)

	self.TmplData["begindate"] = c_begin
	self.TmplData["enddate"] = c_end

	return true
}

func (self *FailStatisticsObj) SqlQueryExecute() {
	failstatis := *common.FetchAllRowsPtr(
		`SELECT FAILDESC, COUNT(FAILDESC) AS CNT 
		   FROM SFC_SSNFLOW(NOLOCK) 
		  WHERE RESULT='FAIL' AND MODIFYDATE BETWEEN ?
		    AND ? 
		  GROUP BY FAILDESC 
		  ORDER BY CNT DESC`,
		self.Usr.Conn, new(common.NormalStruct), self.Sqlparas...)

	self.TmplData["failstatis"] = failstatis
}

func FailStatisticsHandler(ctx *web.Context) {
	self := new(FailStatisticsObj)
	self.Ctx = ctx
	self.Html = "failstatistics.html"
	self.Rightlist = []string{"failstatistics"}
	self.DoQuery(self)
}

func (self *FailStatisticsDetailObj) ParameterCheck() bool {
	s_desc := self.Ctx.Params["fdes"]
	s_bdate := self.Ctx.Params["bdate"]
	s_edate := self.Ctx.Params["edate"]
	s_nm := self.Ctx.Params["nm"]

	if s_desc == "" || s_bdate == "" || s_edate == "" {
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_desc)
	self.Sqlparas = append(self.Sqlparas, s_bdate)
	self.Sqlparas = append(self.Sqlparas, s_edate)
	self.TmplData["fdesc"] = s_desc
	self.TmplData["bdate"] = s_bdate
	self.TmplData["edate"] = s_edate

	rec_curr, _ := strconv.Atoi(s_nm)
	total_id := rec_curr / 50
	if rec_curr%50 > 0 {
		total_id++
	}

	self.TmplData["total_page"] = total_id

	return true
}

func (self *FailStatisticsDetailObj) SqlQueryExecute() {
	dt_ls := *common.FetchAllRowsPtr(
		`SELECT TOP 50 ROW_NUMBER() OVER(ORDER BY SSN_NO, MODIFYDATE), WONO, SSN_NO, CURR_STATION, 
				 RESULT, ISNULL(FAILCODE, ''), ISNULL(FAILDESC, ''), CONVERT(CHAR(23), MODIFYDATE, 121) 
		   FROM SFC_SSNFLOW(NOLOCK)
		  WHERE FAILDESC=?
		    AND MODIFYDATE BETWEEN ? AND ?`,
		self.Usr.Conn, new(common.WoFailInfo), self.Sqlparas...)

	self.TmplData["dt_ls"] = dt_ls
	self.TmplData["curr_page"] = "1"
}

func FailStatisDetailHandler(ctx *web.Context) {
	self := new(FailStatisticsDetailObj)
	self.Ctx = ctx
	self.Html = "failstatisdetail.html"
	self.Rightlist = []string{"failstatistics"}
	self.DoQueryUrl(self)
}

func (self *FailStatisticsPageObj) ParameterCheck() bool {
	s_desc := self.Ctx.Params["fdes"]
	s_bdate := self.Ctx.Params["bdate"]
	s_edate := self.Ctx.Params["edate"]
	s_page := self.Ctx.Params["pageid"]
	if s_desc == "" || s_bdate == "" || s_edate == "" {
		return false
	}
	pageid, err := strconv.Atoi(s_page)
	if err != nil {
		return false
	}
	idx := 50 * (pageid - 1)

	self.Sqlparas = append(self.Sqlparas, s_desc)
	self.Sqlparas = append(self.Sqlparas, s_bdate)
	self.Sqlparas = append(self.Sqlparas, s_edate)
	self.Sqlparas = append(self.Sqlparas, idx)

	return true
}

func (self *FailStatisticsPageObj) SqlQueryExecute() {
	dt_ls := *common.FetchAllRowsPtr(
		`SELECT TOP 50 A.AUTOID, A.WONO, A.SSN_NO, A.CURR_STATION, A.RESULT, A.FAILCODE, A.FAILDESC, A.MODIFYDATE
           FROM
                (
                	SELECT ROW_NUMBER() OVER(ORDER BY SSN_NO, MODIFYDATE) AS AUTOID, WONO, SSN_NO, CURR_STATION, 
						 	RESULT, ISNULL(FAILCODE, '') AS FAILCODE, ISNULL(FAILDESC, '') AS FAILDESC, CONVERT(CHAR(23), MODIFYDATE, 121) AS MODIFYDATE
				      FROM SFC_SSNFLOW(NOLOCK)
				     WHERE FAILDESC=?
				       AND MODIFYDATE BETWEEN ? AND ?
				) A
		  WHERE A.AUTOID > ?`,
		self.Usr.Conn, new(common.WoFailInfo), self.Sqlparas...)

	dict_js, _ := json.Marshal(map[string]interface{}{"statis": dt_ls, "lang": self.Lang})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func SplitFailStatisByPageHandler(ctx *web.Context) {
	self := new(FailStatisticsPageObj)
	self.Ctx = ctx
	self.DoJsonQuery(self)
}
